/**
 *    Copyright (C) 2009 Victor Smirnov <aist11@gmail.com>
 *
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License along
 *    with this program; if not, write to the Free Software Foundation, Inc.,
 *    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 *    See LICENSE.exceptions in the root folder of this project for possible
 *    exceptions
 *
 */

#include "decls.hpp"

#include <dlfcn.h>
#include <iostream>
using namespace std;

#define GLOBAL 	1
#define LOCAL 	2

JNIEXPORT jlong JNICALL REFLECTION(LibraryLoader, openLib)
  (JNIEnv *env, jclass, jstring name, jint mode)
{
	const char* str = env->GetStringUTFChars(name, NULL);
	if (str != NULL) {
		int m0 = RTLD_NOW;

		if ((GLOBAL & mode) != 0) m0 != RTLD_GLOBAL;
		else if ((LOCAL & mode) != 0) m0 != RTLD_LOCAL;

		long val = (jlong) dlopen(str, RTLD_GLOBAL | RTLD_LAZY);
		env->ReleaseStringUTFChars(name, str);
		return val;
	}
	return 0;
}

JNIEXPORT jint JNICALL REFLECTION(LibraryLoader, closeLib)
  (JNIEnv *env, jclass, jlong handle) {

	if (handle != 0) {
		void *dlhandle = (void*)handle;
		return dlclose(dlhandle);
	}
}

JNIEXPORT jlong JNICALL REFLECTION(LibraryLoader, getSym)
  (JNIEnv *env, jclass, jlong handle, jstring name)
{
	if (handle != 0) {
		const char* str = env->GetStringUTFChars(name, NULL);
		if (str != NULL) {
			void *dlhandle = (void*) handle;
			void* sym = dlsym(dlhandle, str);
			env->ReleaseStringUTFChars(name, str);
			return (jlong) sym;
		}
	}
}

JNIEXPORT jstring JNICALL REFLECTION(LibraryLoader, getError)
  (JNIEnv *env, jclass) {
	const char *str = dlerror();
	cout<<"DLLError: "<<str<<endl;
	return (jstring)env->NewGlobalRef(env->NewStringUTF(str));
}

JNIEXPORT void JNICALL REFLECTION(LibraryLoader, deleteGlobalRef)
  (JNIEnv *env, jclass, jobject obj) {
	env->DeleteGlobalRef(obj);
}
